package manager.com.ithei.edu.info.manager.dao;

import manager.com.ithei.edu.info.manager.domain.Student;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;

public class StudentDao implements BaseStudentDao{
    // 创建学生对象数组
    //静态代码块执行顺序
    private static Student[] stus = new Student[5];
    static{
        System.out.println("- - - - - - - - - - loading...........");
        Student stu1= null;
        try {
            stu1 = new Student("hiema001","liuguansheng","22","1999-10-03","安徽省安庆市怀宁县");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Student stu2= null;
        try {
            stu2 = new Student("hiema002","张三","32","1989-10-03","安徽省合肥市瑶海区");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        stus[1]=stu1;
        stus[2]=stu2;
    }
    // 添加学生方法
    @Override
    public boolean addStudent(Student stu) {

        // 2. 添加学生到数组
        //2.1 定义变量index为-1，假设数组已经全部存满，没有null的元素
        int index = -1;
        //2.2 遍历数组取出每一个元素，判断是否是null
        for (int i = 0; i < stus.length; i++) {
            Student student = stus[i];
            if(student == null){
                index = i;
                //2.3 如果为null，让index变量记录当前索引位置，并使用break结束循环遍历
                break;
            }
        }

        // 3. 返回是否添加成功的boolean类型状态
        if(index == -1){
            // 装满了
            return false;
        }else{
            // 没有装满, 正常添加, 返回true
            stus[index] = stu;
            return true;
        }
    }
    // 查看学生方法
    @Override
    public Student[] findAllStudent() {
        return stus;
    }

    @Override
    public void deleteStudentByIdTwo(String id) {
        stus[getIndex(id)]=null;
    }

    //获取学号对应对象的索引
    @Override
    public int getIndex(String id){
        int index = -1;
        for (int i = 0; i < stus.length; i++) {
            Student stu = stus[i];
            if(stu != null && stu.getSid().equals(id)){
                index = i;
                break;
            }
        }
        return index;
    }

    //设置学生对象
    @Override
    public void setStudentByIdTwo(String id, Student stu) {
        //通过学号查找数组中对应的索引值
        int index=getIndex(id);
        //让给定学生对象覆盖指定索引位置的元素(对象)
        stus[index]=stu;
    }
}
